//
//  ForgetPWVC.m
//  NtoccDriver
//
//  Created by mac on 2019/11/18.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "ForgetPWVC.h"
#import "UpLoadImaeVC.h"
#import "LogInVC.h"
#import "ImgVAouthCode.h"
@interface ForgetPWVC (){
    int timeOld;
    int timeNew;
}
@property (nonatomic,strong) CJImageView *imgVSelect;
@property (nonatomic,copy) NSString *strSelect; // 0  1

@property (nonatomic,strong) CJTextField *fieldOldPhone;
@property (nonatomic,strong) CJTextField *fieldNewPhone;
@property (nonatomic,strong) CJView *viewNewPhone;
@property (nonatomic,strong) CJTextField *fieldVCode; // 验证码
@property (nonatomic,strong) CJTextField *fieldNewPW;
@property (nonatomic,strong) CJTextField *filedSurePW;

// 信息上传部分
@property (nonatomic,strong) CJView *viewImgVBG;
@property (nonatomic,strong) FlexTouchView *touchGetOldCode;
@property (nonatomic,strong) FlexTouchView *touchGetNewCode;

@property (nonatomic,copy) NSString *strIdImg; // 反面
@property (nonatomic,copy) NSString *strIdBackImg;
@property (nonatomic,copy)  NSString *strIdInhandImg;
//@property (nonatomic,copy) NSString *strLicenseImg;
@property (nonatomic,strong) CJLabel *labIdImg;
@property (nonatomic,strong) CJLabel *labIdBackImg;
@property (nonatomic,strong) CJLabel *labIdInhandImg;
@property (nonatomic,strong) CJLabel *labLicenseImg;

@property (nonatomic,strong) CJLabel *labOldCode;
@property (nonatomic,strong) CJLabel *labNewCode;
@property (nonatomic,copy) NSString *judge;//是否更换手机号 0不更换 1更换

@property (nonatomic,copy) NSString *strSecureTextEntry;  //1 加密  0 不加密
@property (nonatomic,strong) UIImageView *imgSecureEntry;
@property (nonatomic,copy) NSString *strBranchCode; // 机构code
@property (nonatomic,strong) CJTextField *fieldBranchCode;
@property (nonatomic,strong) FlexTouchView *touvhViewGetBranchCode;
@property (nonatomic,strong) UIView *viewBranchLine;

@end

@implementation ForgetPWVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"忘记密码")];
    [self setBackLeftButton:@""];
    [self setDefaultValue];
    [self createView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.touvhViewGetBranchCode.userInteractionEnabled = YES;
    @weakify(self);
    [CJNetWork getBrachcCodeSuccess:^(id  _Nullable responseObject) {
        
        @strongify(self);
        if ([CJControl getHideBranche]) {
            self.touvhViewGetBranchCode.hidden = YES;
            self.viewBranchLine.hidden = YES;
        }else{
            self.touvhViewGetBranchCode.hidden = NO;
            self.viewBranchLine.hidden = NO;
        }
    }];
    [CJNetWork getBrachcCodeListSuccess:^(id  _Nullable responseObject) {

        @strongify(self);
        NSArray *list = (NSArray *)responseObject;
        if (list.count > 0) {
            NSDictionary *dic = list[0];
            self.fieldBranchCode.text = [CJControl getThreeUnaryValueStr:dic[@"groupName"]];
            self.strBranchCode = [CJControl getThreeUnaryValueStr:dic[@"code"]];
        }
    }];
}

- (void)setDefaultValue{
    self.strSelect = @"0";
    self.viewNewPhone.hidden = YES;
    self.viewImgVBG.hidden = YES;
    self.judge = @"0";
    self.strIdImg = @"";// 反面
    self.strIdBackImg = @"";
    self.strIdInhandImg = @"";
    self.strSecureTextEntry = @"";
    self.strBranchCode = @"";
}

- (void)createView{
    
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:@"ForgetPWHewaderView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;
    self.labOldCode.backgroundColor = [UIColor cjMainColor];
    
    if (@available(iOS 12.0, *)) {
        self.fieldNewPW.textContentType = UITextContentTypeOneTimeCode;
        self.fieldOldPhone.textContentType = UITextContentTypeOneTimeCode;
    } else {
        // Fallback on earlier versions
    }
    
    [header layoutIfNeeded];
    [self.view addSubview:header];
    
}

//是否选中
- (void)selecImgvAction{
    [self.view endEditing:NO];
    if ([self.strSelect isEqualToString:@"0"]) {
        self.strSelect = @"1";
        self.imgVSelect.image = [UIImage imageNamed:@"selected"];
        self.viewNewPhone.hidden = NO;
        self.viewImgVBG.hidden = NO;
        self.touchGetOldCode.hidden = YES;
        self.judge = @"1";
    } else {
        self.strSelect = @"0";
        self.imgVSelect.image = [UIImage imageNamed:@"zcj_unSelected"];
        self.viewNewPhone.hidden = YES;
        self.viewImgVBG.hidden = YES;
        self.touchGetOldCode.hidden = NO;
        self.judge = @"0";
    }
    self.touvhViewGetBranchCode.userInteractionEnabled = YES;
}

- (void)btnActionSecureTextEntry{
    
    if ([self.strSecureTextEntry isEqualToString:@"1"]) {
        self.strSecureTextEntry = @"0";
        self.imgSecureEntry.image = [UIImage imageNamed:@"icon_open_eye"];
        self.fieldNewPW.secureTextEntry = NO;
        self.filedSurePW.secureTextEntry = NO;
    }else{
        self.strSecureTextEntry = @"1";
        self.imgSecureEntry.image = [UIImage imageNamed:@"icon_close_eye"];
        self.fieldNewPW.secureTextEntry = YES;
        self.filedSurePW.secureTextEntry = YES;
    }
}

- (void)getOldPhoneVerCodeAction{

    [self.view endEditing:NO];
    if (IsStrEmpty(self.fieldOldPhone.text) || ![CJRegular getcheckPhone:self.fieldOldPhone.text]) {
         [[[AFViewShaker alloc] initWithView:self.fieldOldPhone] shakeWithDuration:[ShakerTime floatValue] completion:^{
             [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];

         }];
    }else if([[CJControl getThreeUnaryValueStr:self.strBranchCode] isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];

    }else{
    
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/party/validPhoneNoError",CJBaseUrl);
        NSDictionary *dicPar = @{@"phone":CJStringWithFormat(@"%@",self.fieldOldPhone.text),
                                 @"branchCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
                                };
        @weakify(self);
        [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
//            {
//                "msg": "手机号没有注册",
//                "data": "no",
//                "status": 0
//            }
//            {
//                "msg": "手机号已注册",
//                "data": "yes",
//                "status": 0
//            }
//
            NSString *strData = (NSString *)responseObject;
            
            if ([strData isEqualToString:@"yes"]) {

                [[ImgVAouthCode shared] initWithPhoneNum:self.fieldOldPhone.text ClickOnSure:^(NSString * _Nonnull strSure) {
                    @strongify(self);
                    [self getAouthCodeWithOldPhoneWithImageCode:strSure];
                 } ClickOnCancle:^(NSString * _Nonnull strCancle) {
                     
                 }];

            }else{
                [CJAlert showStringDismissWithDelay:@"手机号没有注册"];
            }
            
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);

        }];
    }
}

- (void)getAouthCodeWithOldPhoneWithImageCode:(NSString *)imgVCode{
    
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/sms/sendVerificationCode",CJBaseUrl);
        NSDictionary *dicPar = @{
            @"phone":CJStringWithFormat(@"%@",self.fieldOldPhone.text),
            @"partyGroupCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
            @"imageCode":imgVCode
        };
    
        @weakify(self);
        [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
            @strongify(self);
            self.touvhViewGetBranchCode.userInteractionEnabled = NO;
            self.touchGetOldCode.userInteractionEnabled = NO;
            self.touchGetOldCode.backgroundColor = [UIColor cjMainColor];
            timeOld = 60;
            [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireOdlM:) userInfo:nil repeats:YES];

        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);

        }];
}

- (void)timerFireOdlM:(NSTimer *)theTimer{
    
    NSString * str =[NSString stringWithFormat:@"(%ds)",timeOld];
//    [self.btnGetCode setTitle:str forState:UIControlStateNormal];
    self.labOldCode.text = str;
    timeOld--;
    if (timeOld==0) {
        [theTimer invalidate];
        timeOld=60;
//        [self.btnGetCode setTitle:@"验证码" forState:UIControlStateNormal];
        self.labOldCode.text = @"验证码";
        self.touchGetOldCode.userInteractionEnabled = YES;
        self.labOldCode.backgroundColor = [UIColor cjMainColor];
    }
}

//
- (void)getVerCodeAction{

    [self.view endEditing:NO];
    if (IsStrEmpty(self.fieldNewPhone.text) || ![CJRegular getcheckPhone:self.fieldNewPhone.text]) {
         [[[AFViewShaker alloc] initWithView:self.fieldNewPhone] shakeWithDuration:[ShakerTime floatValue] completion:^{
             [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];
         }];
    }else if([[CJControl getThreeUnaryValueStr:self.strBranchCode] isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];

    }else{
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/party/validPhoneNoError",CJBaseUrl);
        NSDictionary *dicPar = @{
            @"phone":CJStringWithFormat(@"%@",self.fieldNewPhone.text),
            @"branchCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
        };

        @weakify(self);
        [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
            
            NSString *strData = (NSString *)responseObject;
            
            if ([strData isEqualToString:@"no"]) {
//                [ws getAouthCodeWithNewhoneWithImageCode:];
                [[ImgVAouthCode shared] initWithPhoneNum:self.fieldNewPhone.text ClickOnSure:^(NSString * _Nonnull strSure) {
                    @strongify(self);
                    [self getAouthCodeWithNewhoneWithImageCode:strSure];
                 } ClickOnCancle:^(NSString * _Nonnull strCancle) {
                     
                 }];
            }else{
                [CJAlert showStringDismissWithDelay:@"手机号已注册"];
            }
            
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);

        }];
    }
    
}

- (void)getAouthCodeWithNewhoneWithImageCode:(NSString *)imgVCode{
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/sms/sendVerificationCode",CJBaseUrl);
    NSDictionary *dicPar = @{
        @"phone":CJStringWithFormat(@"%@",self.fieldNewPhone.text),
        @"partyGroupCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
        @"imageCode":imgVCode
    };

    @weakify(self);
    [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

        @strongify(self);
        self.touchGetNewCode.userInteractionEnabled = NO;
        self.touvhViewGetBranchCode.userInteractionEnabled = NO;
        self.touchGetNewCode.backgroundColor = [UIColor cjMainColor];
        timeNew = 60;
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireNewM:) userInfo:nil repeats:YES];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);

    }];

}

- (void)timerFireNewM:(NSTimer *)theTimer{
    
    NSString * str =[NSString stringWithFormat:@"(%ds)",timeNew];
//    [self.btnGetCode setTitle:str forState:UIControlStateNormal];
    self.labNewCode.backgroundColor = [UIColor cjMainColor];
    self.labNewCode.textColor = [UIColor cjWhiteColor];
    self.labNewCode.text = str;
    timeNew--;
    if (timeNew==0) {
        [theTimer invalidate];
        timeNew=60;
//        [self.btnGetCode setTitle:@"验证码" forState:UIControlStateNormal];
        self.labNewCode.text = @"验证码";
        self.touchGetNewCode.userInteractionEnabled = YES;
        self.touchGetNewCode.backgroundColor = [UIColor cjMainColor];
    }
}

//反面
- (void)upLoadIDImageVNegative{
    
    UpLoadImaeVC *vc = [[UpLoadImaeVC alloc]init];
    vc.strTitle = @"身份证国徽面照片";
    vc.strImgUrl = self.strIdBackImg;
    vc.strSampleImg = @"yangtu3";
    @weakify(self);
    vc.blcokSuccee = ^(id anyObject) {
        @strongify(self);
        self.strIdBackImg = (NSString *)anyObject;
        self.labIdBackImg.text = @"身份证国徽面照片已上传(点击修改)";
        self.labIdBackImg.textColor = [UIColor cjMainColorText];
    };
    [self pushVc:vc];
}
//正面
- (void)upLoadIDImageVPositive{
    
    UpLoadImaeVC *vc = [[UpLoadImaeVC alloc]init];
    vc.strTitle = @"身份证人像面照片";
    vc.strImgUrl = self.strIdImg;
    vc.strSampleImg = @"yangtu4";
    @weakify(self);
    vc.blcokSuccee = ^(id anyObject) {
        @strongify(self);
        self.strIdImg = (NSString *)anyObject;
        self.labIdImg.text = @"身份证人像面照片已上传(点击修改)";
        self.labIdImg.textColor = [UIColor cjMainColorText];
    };
    [self pushVc:vc];
}
// 手持照片
- (void)upLoadIDImageVWithPerson{
    
    UpLoadImaeVC *vc = [[UpLoadImaeVC alloc]init];
    vc.strTitle = @"手持身份证合照";
    vc.strSampleImg = @"yangtu2";
    vc.strImgUrl = self.strIdInhandImg;
    @weakify(self);
    vc.blcokSuccee = ^(id anyObject) {
        @strongify(self);
        self.strIdInhandImg = (NSString *)anyObject;
        self.labIdInhandImg.text = @"手持身份证合照已上传(点击修改)";
        self.labIdInhandImg.textColor = [UIColor cjMainColorText];
    };
    [self pushVc:vc];
}
// 企业营业执照
//- (void)upLoadIDImagVBusinessLicense{
//    UpLoadImaeVC *vc = [[UpLoadImaeVC alloc]init];
//    vc.strTitle = @"上传企业营业执照";
//    vc.strSampleImg = @"yangtu1";
//    vc.strImgUrl = self.strLicenseImg;
//    @weakify(self);
//    vc.blcokSuccee = ^(id anyObject) {
//        @strongify(self);
//        self.strLicenseImg = (NSString *)anyObject;
//        self.labLicenseImg.text = @"企业营业执照(已上传)";
//        self.labLicenseImg.textColor = [UIColor cjRedColor];
//    };
//    [self pushVc:vc];
//}

- (void)changePassWord{
    
    NSDictionary *dicPra;
    // 不更换手机手机号
    if (self.judge.integerValue == 0) {
        
        if (![CJRegular getcheckPhone:self.fieldOldPhone.text]) {
            [[[AFViewShaker alloc] initWithView:self.fieldOldPhone] shakeWithDuration:[ShakerTime floatValue] completion:^{
                [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];
            }];
        }else if (![CJRegular getSMFAouth:self.fieldVCode.text]){
            [[[AFViewShaker alloc] initWithView:self.fieldVCode] shakeWithDuration:[ShakerTime floatValue] completion:^{
                [CJAlert showStringDismissWithDelay:@"请填写正确验证码"];
            }];
        }else if ([CJRegular getIsStrEmpty:self.fieldNewPW.text]){
            [[[AFViewShaker alloc] initWithView:self.fieldNewPW] shakeWithDuration:[ShakerTime floatValue] completion:^{
                [CJAlert showStringDismissWithDelay:self.fieldNewPW.placeholder];
            }];
        }
        else if (![self.fieldNewPW.text isEqualToString:self.filedSurePW.text]){
            [CJAlert showStringDismissWithDelay:@"两次密码不一致"];
        }else if ([self.strBranchCode isEqualToString:@""]){
            [CJAlert showStringDismissWithDelay:@"请选择机构"];
        }
        else{
            
            dicPra = @{
                @"phone":self.fieldOldPhone.text,
                @"judge":self.judge,
                @"verifyCode":self.fieldVCode.text,
                @"newPwd":[CJControl base64:self.fieldNewPW.text],
                @"branchCode":self.strBranchCode,
                @"userType":@"SHIPMENT",
                @"partyGroupCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
            };
            
            
            NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/party/forgetPass",CJBaseUrl);
            @weakify(self);
            [[HDNetworking sharedHDNetworking] POST:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
                
                @strongify(self);
                NSString *status = CJStringWithFormat(@"%@",responseObject[@"status"]);
                if (status.integerValue == 0) {
                    [self pop];
                }
                
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }
        
    }else{
        
          if (![CJRegular getcheckPhone:self.fieldOldPhone.text]) {
              [[[AFViewShaker alloc] initWithView:self.fieldOldPhone] shakeWithDuration:[ShakerTime floatValue] completion:^{
                  [CJAlert showStringDismissWithDelay:@"请填写正确的原手机号"];
              }];
          }else if (![CJRegular getcheckPhone:self.fieldNewPhone.text]) {
               [[[AFViewShaker alloc] initWithView:self.fieldNewPhone] shakeWithDuration:[ShakerTime floatValue] completion:^{
                   [CJAlert showStringDismissWithDelay:@"请填写正确的新手机号"];
               }];
            }else if (![CJRegular getSMFAouth:self.fieldVCode.text]){
              [[[AFViewShaker alloc] initWithView:self.fieldVCode] shakeWithDuration:[ShakerTime floatValue] completion:^{
                  [CJAlert showStringDismissWithDelay:@"请填写正确验证码"];
              }];
          }else if ([CJRegular getIsStrEmpty:self.fieldNewPW.text]){
              [[[AFViewShaker alloc] initWithView:self.fieldNewPW] shakeWithDuration:[ShakerTime floatValue] completion:^{
                  [CJAlert showStringDismissWithDelay:self.fieldNewPW.placeholder];
              }];
          }else if (![self.fieldNewPW.text isEqualToString:self.filedSurePW.text]){
              [CJAlert showStringDismissWithDelay:@"两次密码不一致"];
          }
          else if ([CJRegular getIsStrEmpty:self.strIdImg]){
              [CJAlert showStringDismissWithDelay:@"请选择上传身份证人像面照片"];
          }else if ([CJRegular getIsStrEmpty:self.strIdBackImg]){
              [CJAlert showStringDismissWithDelay:@"请选择上传身份证国徽面照片"];
          }else if ([CJRegular getIsStrEmpty:self.strIdInhandImg]){
              [CJAlert showStringDismissWithDelay:@"请选择上传手持身份证合照"];
          }
//          else if ([CJRegular getIsStrEmpty:self.strLicenseImg]){
//              [CJAlert showStringDismissWithDelay:@"请选择上传企业营业执照"];
//          }
            else if ([self.strBranchCode isEqualToString:@""]){
                [CJAlert showStringDismissWithDelay:@"请选择机构"];
            }
          else{
              
              dicPra = @{
                  @"phone":self.fieldOldPhone.text,
                  @"newPhone":self.fieldNewPhone.text,
                  @"judge":self.judge,
                  @"verifyCode":self.fieldVCode.text,
                  @"newPwd":[CJControl base64:self.fieldNewPW.text],
                  @"idImg":self.strIdImg,
                  @"idBackImg":self.strIdBackImg,
                  @"idInhandImg":self.strIdInhandImg,
                  @"branchCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
                  @"userType":@"SHIPMENT",
//                  @"licenseImg":self.strLicenseImg
                  @"partyGroupCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
              };
              
              @weakify(self);
              NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/party/forgetPass",CJBaseUrl);
              [[HDNetworking sharedHDNetworking] POST:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
                  
                  @strongify(self);
                  NSString *status = CJStringWithFormat(@"%@",responseObject[@"status"]);
                  if (status.integerValue == 0) {
                      [CJAlert showStringDismissWithDelay:@"重置密码并更换手机号已提交申请，请等待后台管理员审核"];
                      [self pop];
                  }
                  
              } failure:^(NSError * _Nonnull error) {
                  
              }];
              
          }
    }
    
}


#pragma mark ----------选择机构 ----
-(void)btnGetBranchCodeListAction{

    [self.view endEditing:NO];
    @weakify(self);
    [CJNetWork getBrachcCodeListSuccess:^(id  _Nullable responseObject) {
        @strongify(self);
        NSArray *list = (NSArray *)responseObject;
        NSMutableArray *arrMutar = [[NSMutableArray alloc]init];
        NSMutableArray *arrMutarCodes = [[NSMutableArray alloc]init];

        if (list.count > 0) {

            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [arrMutar addObject:obj[@"groupName"]];
                [arrMutarCodes addObject:obj[@"code"]];
            }];
        }
        [self btnSelectList:arrMutar listCodes:arrMutarCodes title:@""];
        
    }];
}


- (void)btnSelectList:(NSArray *)list listCodes:(NSMutableArray *)arryCodes title:(NSString *)strTitle{
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = strTitle;
    stringPickerView.dataSourceArr = list;
    @weakify(self);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        
        @strongify(self);
        self.fieldBranchCode.text = resultModel.selectValue;
        self.strBranchCode = arryCodes[resultModel.index];
   
    };
    
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}



@end
